<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\ProxyHelpers;
use App\Http\Requests\Admin\LoginRequest;
use App\Models\AdminUser;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;


class LoginController extends Controller
{
    use AuthenticatesUsers, ProxyHelpers;

    public function login(LoginRequest $request)
    {
        $user = AdminUser::query()->where('username', $request->username)->first();

        if (!$user) {
            return $this->failed('用户不存在', 401);
        }
        if (!Hash::check($request->password, $user->password)) {
            return $this->failed('密码不正确');
        }

        $user->last_login_at = Carbon::now()->toDateTimeString();
        $user->save();

        $token = $this->authenticate();
        return $this->success(['token' => $token, 'user' => $user]);
    }

    public function logout()
    {
        if (Auth::guard('admin')->check()) {
            Auth::guard('admin')->user()->token()->delete();
        }
    }
}
